package cn.example.filepersistancetest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.TextUtils;
import android.widget.EditText;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class MainActivity extends AppCompatActivity {

    private EditText editText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = findViewById(R.id.edit_text);
        // 读取文件
        String fileText = "";
        FileInputStream in = null;
        BufferedReader reader = null;

        try {
            in = openFileInput("data");
            reader =  new BufferedReader(new InputStreamReader(in));
            fileText = reader.readLine();
            if(!TextUtils.isEmpty(fileText)){
                editText.setText(fileText);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(null != reader)
                    reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 写入文件
        String inputText = editText.getText().toString();
        FileOutputStream out = null;
        BufferedWriter writer = null;
        try {
            out = openFileOutput("data", MODE_PRIVATE);
            writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(inputText);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(null != writer)
                 writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}